import { toRaw } from 'vue'
import { getDomAttributeByFolderId } from '@Untils'
let _temp_id = null
let dragStart = (binding, e) => {
  _temp_id = binding.instance.info.id

  let { dom } = getDomAttributeByFolderId(e)
  dom.style.backgroundColor = 'rgb(204,232,255)'
  e.dataTransfer.setData('instance', JSON.stringify(binding.instance.info))
  e.dataTransfer.dropEffect = 'move'
  e.dataTransfer.effectAllowed = 'move'

  //e.dataTransfer.setDragImage(e.target, 10, 10)
}

let dragEnd = (binding, e) => {
  let { dom } = getDomAttributeByFolderId(e)
  dom.style.backgroundColor = null
}

let drop = (binding, e) => {
  e.preventDefault()
  var data = JSON.parse(e.dataTransfer.getData('instance'))

  let { dom } = getDomAttributeByFolderId(e)
  dom.style.backgroundColor = null

  //不能自己移动到自己目标上面
  if (!(binding.instance.info.id == data.id)) {
    binding.instance.reposDrop(data)
  }
  _temp_id = null
}

let dragOver = (e) => {
  let { dom } = getDomAttributeByFolderId(e)
  dom.style.backgroundColor = 'rgb(204,232,255)'
  e.preventDefault()
}

let dragOut = (binding, e) => {
  let { dom } = getDomAttributeByFolderId(e)

  if (binding.instance.info.id != _temp_id) {
    dom.style.backgroundColor = null
  }
  e.preventDefault()
}

export default () => {
  return {
    mounted(el, binding) {
      el.draggable = true
      el.addEventListener('dragstart', dragStart.bind(null, binding))
      el.addEventListener('dragend', dragEnd.bind(null, binding))
      el.addEventListener('dragover', dragOver)
      el.addEventListener('dragleave', dragOut.bind(null, binding))
      el.addEventListener('drop', drop.bind(null, binding))
    },
    beforeUnmount(el) {
      el.removeEventListener('dragstart', dragStart)
      el.removeEventListener('drop', drop)
      el.removeEventListener('dragover', dragOver)
      el.removeEventListener('dragend', dragEnd)
      el.addEventListener('dragleave', dragOut)
    },
  }
}
